/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.primitives.stdlib;

import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InterruptedIOException;

import fr.x9c.cadmium.kernel.Channel;
import fr.x9c.cadmium.kernel.CodeRunner;
import fr.x9c.cadmium.kernel.DataFormat;
import fr.x9c.cadmium.kernel.Fail;
import fr.x9c.cadmium.kernel.FalseExit;
import fr.x9c.cadmium.kernel.Fatal;
import fr.x9c.cadmium.kernel.Primitive;
import fr.x9c.cadmium.kernel.PrimitiveProvider;
import fr.x9c.cadmium.kernel.Value;
import fr.x9c.cadmium.util.IO;
import fr.x9c.cadmium.util.Misc;

/**
 * Implements all primitives from 'intern.c'.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
@PrimitiveProvider
public final class Intern {

    /**
     * No instance of this class.
     */
    private Intern() {
    } // end empty constructor

    /**
     * Reads a value from an input channel.
     * @param ctxt context
     * @param channel input channel
     * @return value read from <tt>channel</tt>
     * @throws Fail.Exception if data is incorrect
     * @throws Fail.Exception if an i/o error occurs
     * @throws Fatal.Exception if data contains an unsupported element
     *                         (<i>e. g.</i> a 64-bit element)
     */
    @Primitive
    public static Value caml_input_value(final CodeRunner ctxt,
                                         final Value channel)
        throws Fail.Exception, Fatal.Exception, FalseExit {
        final DataInput in =
            ((Channel) channel.asBlock().asCustom()).asDataInput();
        try {
            return fr.x9c.cadmium.kernel.Intern.inputVal(ctxt.getContext(),
                                                         in,
                                                         true);
        } catch (final InterruptedIOException iioe) {
            final FalseExit fe =
                FalseExit.createFromContext(ctxt.getContext());
            fe.fillInStackTrace();
            throw fe;
        } catch (final IOException ioe) {
            Sys.sysError(null, ioe.toString());
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'caml_input_value(CodeRunner, Value)'

    /**
     * Reads a value from a substring.
     * @param ctxt context
     * @param s string to read value from
     * @param offset offset of substring in <tt>s</tt>
     * @return value read from <tt>channel</tt>
     * @throws Fail.Exception if data is incorrect
     * @throws Fail.Exception if an i/o error occurs
     * @throws Fatal.Exception if data contains an unsupported element
     *                         (<i>e. g.</i> a 64-bit element)
     */
    @Primitive
    public static Value caml_input_value_from_string(final CodeRunner ctxt,
                                                     final Value s,
                                                     final Value offset)
        throws Fail.Exception, Fatal.Exception, FalseExit {
        final byte[] b = s.asBlock().getBytes();
        final int ofs = offset.asLong();
        final DataInput in =
            new DataInputStream(new ByteArrayInputStream(b,
                                                         ofs,
                                                         b.length - ofs));
        try {
            return fr.x9c.cadmium.kernel.Intern.inputVal(ctxt.getContext(),
                                                         in,
                                                         true);
        } catch (final InterruptedIOException iioe) {
            final FalseExit fe =
                FalseExit.createFromContext(ctxt.getContext());
            fe.fillInStackTrace();
            throw fe;
        } catch (final IOException ioe) {
            Sys.sysError(null, ioe.toString());
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'caml_input_value_from_string(CodeRunner, Value, Value)'

    /**
     * Determines the size of a marshalled value.
     * @param ctxt context
     * @param buff buffer containing marshalled value
     * @param offset offset of marshalled value in <tt>buff</tt>
     * @return the size of the marshalled value
     * @throws Fail.Exception if data is incorrect
     * @throws Fail.Exception if an i/o error occurs
     * @throws Fatal.Exception if data contains an unsupported element
     *                         (<i>e. g.</i> a 64-bit element)
     */
    @Primitive
    public static Value caml_marshal_data_size(final CodeRunner ctxt,
                                               final Value buff,
                                               final Value offset)
        throws Fail.Exception, Fatal.Exception, FalseExit {
        final byte[] b = buff.asBlock().getBytes();
        final int ofs = offset.asLong();
        final DataInput in =
            new DataInputStream(new ByteArrayInputStream(b,
                                                         ofs,
                                                         b.length - ofs));
        try {
            if (IO.read32s(in) != DataFormat.MAGIC_NUMBER) {
                Fail.failWith("Marshal.data_size: bad object");
            } // end if
            return Value.createFromLong(Misc.ensure32s(IO.read32u(in)));
        } catch (final InterruptedIOException iioe) {
            final FalseExit fe =
                FalseExit.createFromContext(ctxt.getContext());
            fe.fillInStackTrace();
            throw fe;
        } catch (final IOException ioe) {
            Sys.sysError(null, ioe.toString());
            return Value.UNIT; // never reached
        } // end try/catch
    } // end method 'caml_marshal_data_size(CodeRunner, Value, Value)'

} // end class 'Intern'
